<template>
  <el-table
    v-if="tableData.length"
    :data="tableData"
    style="width: 100%"
    :default-sort="{ prop: 'durationInMinutes', order: 'descending' }"
    show-summary
    :summary-method="getSummaries"
  >
    <el-table-column fixed="right" label="Operations" width="120">
      <template #default="scope">
        <el-button link type="primary" @click="handleDetails(scope.row)">
          Details
        </el-button>
      </template>
    </el-table-column>
    <el-table-column prop="testCase" label="Test Case" sortable />
    <el-table-column prop="StartCaseTime" label="Start Time" sortable />
    <el-table-column prop="EndCaseTime" label="End Time" sortable />
    <el-table-column prop="durationInMinutes" label="Duration (minutes)" sortable />
    <el-table-column prop="Success" label="Status">
      <template #default="scope">
        <el-tag :type="scope.row.Success ? 'success' : 'danger'">
          {{ scope.row.Success ? 'Success' : 'Failed' }}
        </el-tag>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup>
import { ElTable, ElTableColumn, ElTag, ElButton } from 'element-plus';
const props = defineProps({
  tableData: {
    type: Array,
    required: true
  }
});

const emit = defineEmits(['details']);

const handleDetails = (row) => {
  emit('details', row);
};

const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = 'Total';
      return;
    }
    if (column.property === 'durationInMinutes') {
      const values = data.map(item => Number(item[column.property]));
      sums[index] = values.reduce((prev, curr) => {
        return prev + curr;
      }, 0);
      sums[index] = Number(sums[index].toFixed(2));
    } else {
      sums[index] = '';
    }
  });
  return sums;
};
</script>
